<template>
    <el-container style="height: 100%;">
        <el-main class="mainstyle">
            <div style="width: 70%;">
                <div>
                    <input placeholder="Q   搜索历史记录" v-model="searchQuery" class="research_input" />
                    <el-date-picker v-model="value1" type="daterange" range-separator="To"
                        start-placeholder="Start date" end-placeholder="End date" :size="small"
                        style="background-color: antiquewhite; height: 40px; width: 30%; margin-left: 5%;" />
                </div>
                <div v-if="history.size == 0">
                    <p>没有生成记录</p>
                </div>
                <div v-for="(item, index) in filteredHistory" :key="index">
                    <div @click="goToHome" class="history_button">
                        <div
                            style="margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center">
                            <div style="margin-top: 7px; display: flex; align-items: center">
                                <el-icon v-if="item.type === 1" size="16" style="margin-left:12px">
                                    <Document />
                                </el-icon>
                                <el-icon v-else size="16" style="margin-left:12px">
                                    <Picture />
                                </el-icon>
                                <div v-if="item.editing" @click.stop>
                                    <div style="display: flex; align-items: center;">
                                        <el-input style="height: 21px; width: 450px;" v-model="item.newText" />
                                        <el-icon style="margin-left: 5px;" @click="saveText(index)">
                                            <Check />
                                        </el-icon>
                                    </div>
                                </div>
                                <div v-else>
                                    <span style="margin-left:10px; font-size: 14px">{{ item.generateId }}</span>
                                </div>
                            </div>
                            <div style="margin-top: 7px; display: flex; align-items: center;">
                                <span style="margin-right: 8px; font-size: 12px">{{ item.date }}</span>
                                <el-dropdown style="margin-right: 8px">
                                    <el-icon size="12" style="outline: none" @click.stop>
                                        <MoreFilled />
                                    </el-icon>
                                    <template #dropdown>
                                        <el-dropdown-menu class="dropdown_menu">
                                            <el-dropdown-item @click="removehistory(index)">删除</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                        </div>

                        <div style="display: flex; flex-wrap: wrap">
                            <div v-for="(pictureUrl, pictureIndex) in item.picture" :key="pictureIndex">
                                <el-image @click.stop="openImageModal(pictureUrl, item)"
                                    style="margin-top: 5px; margin-left: 20px; margin-bottom: 8px; height: 64px; min-width: 64px; width: auto; border-radius: 8px;"
                                    :src="pictureUrl" :fit='cover' />
                            </div>
                        </div>
                    </div>
                </div>
                <div style="margin-top: 20px; display: flex; justify-content: center;">
                    <el-pagination style="" background layout="prev, pager, next" :total="totalNum"
                        :current-page="currentPage" @current-change="handlePageChange" />
                </div>
            </div>
        </el-main>
        <el-dialog v-model="imageModalVisible" :show-close="true" :close-on-click-modal="ture" class="image-modal"
            width="80%">
            <div class="modal-content">
                <div class="modal-body">
                    <div class="image-container">
                        <el-image :src="selectedImage" fit="contain" style="width: 100%; height: 100%;" />
                    </div>
                    <div class="details-container">
                        <div class="action-buttons">
                            <div class="action-btn" @click="handleSave">
                                <el-icon size="20">
                                    <Document />
                                </el-icon>
                                <span>保存</span>
                            </div>
                            <div class="action-btn">
                                <el-icon size="20">
                                    <PictureFilled />
                                </el-icon>
                                <span>收藏</span>
                            </div>
                            <div class="action-btn" @click="handleEdit">
                                <el-icon size="20">
                                    <Brush />
                                </el-icon>
                                <span>编辑</span>
                            </div>
                            <div class="action-btn" @click="handleShare">
                                <el-icon size="20">
                                    <Edit />
                                </el-icon>
                                <span>转发</span>
                            </div>
                        </div>

                        <div class="prompt-section">
                            <h3>提示词</h3>
                            <p>{{ selectedItem.text }}</p>
                        </div>

                        <div class="image-details">
                            <div class="detail-row">
                                <div class="detail-item">
                                    <span>模型</span>
                                    <span>model-version1</span>
                                </div>
                                <div class="detail-item">
                                    <span>日期</span>
                                    <span>{{ selectedItem.date }}</span>
                                </div>
                                <div class="detail-item">
                                    <span>高度</span>
                                    <span>{{ selectedItem.height }}</span>
                                </div>
                                <div class="detail-item">
                                    <span>宽度</span>
                                    <span>{{ selectedItem.width }}</span>
                                </div>
                            </div>
                        </div>

                        <div class="reference-image">
                            <h3>参考图</h3>
                            <el-image :src="selectedImage" fit="contain" style="height: 64px; width: 64px;" />
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </el-container>
</template>


<script>
import { ElNotification } from 'element-plus';
import { useRouter } from 'vue-router';


export default {
    data() {
        return {
            searchQuery: '',
            value1: '',
            history: [],
            imageModalVisible: false,
            selectedImage: null,
            selectItem: null,
            totalNum: 50,
            currentPage: 1,
            router: useRouter()
        };
    },
    methods: {
        getHistory() {
            var url = 'http://localhost:8080/api/image/history?currentPage='
            url += this.currentPage;
            url += '&pageSize=10';
            fetch(url, {
                method: 'GET',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json',
                }
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            }).then(data => {
                data = data['data']
                this.totalNum = data['total'];
                console.log(data['records']);
                // 检查 data['records'] 是否存在且为数组
                if (Array.isArray(data['records'])) {
                    this.history = data['records'].map(record => {
                        const date = new Date(record.generationTime);
                        const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日`;

                        return {
                            // 注意：generationId 应该是 record 的一个属性，而不是变量
                            generateId: record.generationId, // 修正了这里
                            type: record.type + 1,
                            text: record.inputText || '|图生图记录|',
                            date: formattedDate,
                            picture: Array(1).fill(record.generatedImageUrl),
                            editing: false,
                            newText: '',
                            height: record.height,
                            width: record.width
                        };
                    });
                } else {
                    console.error('Expected an array for data["records"], but got:', data['records']);
                }
            }).catch(error => console.error('Error: ', error));
        },
        removehistory(index) {
            var url = 'http://localhost:8080/api/image/';
            url += this.history[index].generateId
            fetch(url, {
                method: 'DELETE',
                credentials: 'include',
                headers: {
                    'Accept': 'application/json',
                }
            }).then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
            }).then(data => {
                if(data['code'] == 200){
                    ElNotification({
                        title: 'Success',
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getHistory(this.currentPage)
                } else {
                    ElNotification({
                        title: 'Error',
                        message: data['msg'],
                        type: 'error'
                    })
                }
            })
        },

        saveText(index) {
            this.history[index].text = this.history[index].newText;
            this.history[index].editing = false;
        },
        openImageModal(pictureUrl, item) {
            this.selectedImage = pictureUrl;
            this.selectedItem = item;
            this.imageModalVisible = true;
        },
        handlePageChange(newPage) {
            console.log(newPage);
            this.currentPage = newPage;
            this.getHistory(newPage);
        },
        handleEdit() {
            localStorage.setItem('imgUrl', this.selectedImage)
            this.router.push('/second_editing')
        },
        handleSave() {
            const link = document.createElement("a");
            link.href = this.selectedImage;
            link.download = 'image.png'
            link.click();
            document.removeChild(link);
        },
        async handleShare() {
            try {
                await navigator.clipboard.writeText(this.selectedImage);
                ElNotification({
                    title: 'URL以复制到剪切板',
                    message: this.selectedImage,
                    type: 'success'
                })
            } catch (err) {
                ElNotification({
                    title: 'Error',
                    message: 'URL复制失败',
                    type: 'error'
                })
            }
        }
    },
    computed: {
        filteredHistory() {
            return this.history.filter(item => item.text.includes(this.searchQuery));
        },
    },
    mounted() {
        this.getHistory(this.currentPage)
    }
};
</script>


<style scoped>
.mainstyle {
    display: flex;
    height: 100%;
    background-color: #F6F4EF;
    justify-content: center;
}

.research_input {
    width: 60%;
    height: 40px;
    margin-top: 10px;
    margin-bottom: 15px;
    padding: 0 12px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #FAECD7;
    box-shadow: 0 0.75px 0.75px 0.75px rgba(0, 0, 0, 0.2);
    transition: border-color 0.3s ease;
    outline: none;
}

.research_input::placeholder {
    color: #837C71;
    font-size: 14px;
}

.history_button {
    margin-top: 15px;
    max-height: 450px;
    height: 100%;
    width: 100%;
    background-color: #FAECD7;
    color: #837C71;
    border-radius: 8px;
    cursor: pointer;
}

.dropdown_menu {
    padding: 5px;
    border-radius: 8px;
}

.dropdown_menu .el-dropdown-menu__item {
    color: #837C71;
    border-radius: 8px;
}

.dropdown_menu .el-dropdown-menu__item:not(.is-disabled):hover {
    color: #837C71;
    background: #F6F4EF;
}

.image-modal {
    border-radius: 12px;
}

.modal-content {
    padding: 20px;
}

.modal-body {
    display: flex;
    gap: 20px;
}

.image-container {
    flex: 1;
    background: #FFF5E6;
    border-radius: 8px;
    overflow: hidden;
}

.details-container {
    flex: 1;
}

.action-buttons {
    display: flex;
    justify-content: space-between;
    margin-bottom: 24px;
}

.action-btn {
    background-color: #FFF5E6;
    border: none;
    color: #837C71;
    padding: 12px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8px;
    width: 22%;
    cursor: pointer;
    font-weight: bold
}

.action-btn:not(.is-disabled):hover {
    background: #F6F4EF;
}

.prompt-section {
    background: #FFF5E6;
    padding: 16px;
    border-radius: 8px;
    margin-bottom: 24px;
}

.prompt-section h3 {
    color: #837C71;
    margin-bottom: 8px;
}

.image-details {
    margin-bottom: 24px;
}

.detail-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
}

.detail-item {
    background: #FFF5E6;
    padding: 12px 12px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    gap: 4px;
    flex: 1;
}

.detail-item span:first-of-type {
    font-weight: bold;
    color: #837C71;
}

.detail-row::after {
    font-weight: bold
}

.reference-image {
    background: #FFF5E6;
    padding: 16px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
}

.reference-image h3 {
    color: #837C71;
    margin-bottom: 16px;
}
</style>
